import { useState, useEffect, createRef } from 'react';
import lr from './index.less';
import api from '@/services';
import { Form, Input, Button, message, Row, Col, Modal } from 'antd';
import {
  UserOutlined,
  LockOutlined,
  SafetyOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
} from '@ant-design/icons';
import { LoginData } from '@/type';

export default function Login(props: any) {
  const getOrderList = async () => {
    const data = await api.getOrderList({ site_id: 0 });
    console.log(data);
  };

  document.title = '登录';

  const [form] = Form.useForm();

  //表单盒子高度自动
  let rgh = createRef<HTMLDivElement>();
  const [height, setHeight] = useState(0);
  const [toggle, setToggle] = useState(false);

  //获取图片验证码
  const [captcha, setCaptcha] = useState({ key: '', img: '' });
  const getCaptcha = async (key?: any) => {
    const data: any = await api.reqCaptcha(key);
    if (data.data.code !== 0) return;
    setCaptcha(data.data.data);
  };

  useEffect(() => {
    setHeight(rgh.current!.clientHeight);
    getCaptcha();
  }, []);

  //登录
  const login = async (params: LoginData) => {
    const data: any = await api.reqLogin(params);
    if (data.data.code !== 0) {
      getCaptcha({ key: captcha.key });
      return message.error(data.data.message);
    }

    message.success(data.data.message);
    sessionStorage.setItem('token', data.data.data.token);
    props.history.replace('/');
  };

  //登录表单验证成功
  const onFinishLogin = (values: any) => {
    values.captcha_key = captcha.key;
    login(values);
  };

  //登录表单验证失败
  const onFinishFailedLogin = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  //注册
  const register = async (params: LoginData) => {
    const data: any = await api.reqRegister(params);
    if (data.data.code !== 0) {
      getCaptcha({ key: captcha.key });
      return message.error(data.data.message);
    }
    form.resetFields();
    Modal.confirm({
      title: '注册成功',
      okText: '去登录',
      onOk() {
        setToggle(false);
        getCaptcha({ key: captcha.key });
      },
    });
  };

  //注册表单验证成功
  const onFinishRegister = (values: any) => {
    values.captcha_key = captcha.key;
    register(values);
  };

  //注册表单验证失败
  const onFinishFailedRegister = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className={lr.contain}>
      <div className={lr.box} style={{ height: `${height}px` }}>
        <div className={lr.wrap}>
          <div className={`${lr.lrbox} ${toggle ? lr.ani : ''}`}>
            {/* 注册表单 */}
            <div className={lr.register} ref={rgh}>
              <div className={lr.photo}></div>
              <div className={lr.form}>
                <h2>多商户管理系统</h2>
                <Form
                  form={form}
                  name="normal_register"
                  className="login-form"
                  validateTrigger="onBlur"
                  onFinish={onFinishRegister}
                  onFinishFailed={onFinishFailedRegister}
                >
                  <Form.Item
                    name="username"
                    rules={[
                      { required: true, message: '请输入账号!' },
                      {
                        pattern: /^[a-zA-Z0-9_]{4,16}$/,
                        message: '用户名包含 字母数字或下划线，长度4~16！',
                      },
                    ]}
                  >
                    <Input
                      prefix={<UserOutlined className="site-form-item-icon" />}
                      placeholder="账号"
                    />
                  </Form.Item>
                  <Form.Item className={lr.rgp}>
                    <Row gutter={2}>
                      <Col span={12}>
                        <Form.Item
                          className={lr.rgpitem}
                          name="password"
                          rules={[
                            { required: true, message: '请输入密码!' },
                            {
                              pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,20}$/,
                              message: '密码至少包含 数字和英文，长度5~20！',
                            },
                          ]}
                        >
                          <Input.Password
                            prefix={
                              <LockOutlined className="site-form-item-icon" />
                            }
                            type="password"
                            placeholder="密码"
                            iconRender={(visible) =>
                              visible ? (
                                <EyeTwoTone />
                              ) : (
                                <EyeInvisibleOutlined />
                              )
                            }
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item
                          className={lr.rgpitem}
                          name="rePassword"
                          rules={[
                            { required: true, message: '请确认密码!' },
                            ({ getFieldValue }) => ({
                              validator(_, value) {
                                if (
                                  !value ||
                                  getFieldValue('password') === value
                                ) {
                                  return Promise.resolve();
                                }
                                return Promise.reject(
                                  new Error('确认密码不正确!'),
                                );
                              },
                            }),
                          ]}
                        >
                          <Input.Password
                            prefix={
                              <LockOutlined className="site-form-item-icon" />
                            }
                            type="rePassword"
                            placeholder="确认密码"
                            iconRender={(visible) =>
                              visible ? (
                                <EyeTwoTone />
                              ) : (
                                <EyeInvisibleOutlined />
                              )
                            }
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form.Item>
                  <Form.Item
                    name="captcha_code"
                    rules={[{ required: true, message: '请输入验证码!' }]}
                  >
                    <Row gutter={2}>
                      <Col span={16}>
                        <Input
                          prefix={
                            <SafetyOutlined className="site-form-item-icon" />
                          }
                          placeholder="验证码"
                        />
                      </Col>
                      <Col span={8}>
                        <div
                          className={lr.captcha}
                          dangerouslySetInnerHTML={{ __html: captcha.img }}
                          onClick={() => {
                            getCaptcha({ key: captcha.key });
                          }}
                        />
                      </Col>
                    </Row>
                  </Form.Item>
                  <Form.Item>
                    <Button
                      type="primary"
                      htmlType="submit"
                      className="login-form-button"
                      block
                    >
                      申请入驻
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <span>已有账号？</span>
                    <Button
                      type="link"
                      onClick={() => {
                        setToggle(false);
                      }}
                    >
                      立即登录
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
            {/* 登录表单 */}
            <div className={lr.login}>
              <div className={lr.photo}></div>
              <div className={lr.form}>
                <h2>多商户管理系统</h2>
                <Form
                  name="normal_login"
                  className="login-form"
                  initialValues={{ username: 'shop', password: '12345' }}
                  onFinish={onFinishLogin}
                  onFinishFailed={onFinishFailedLogin}
                >
                  <Form.Item
                    name="username"
                    rules={[{ required: true, message: '请输入账号!' }]}
                  >
                    <Input
                      prefix={<UserOutlined className="site-form-item-icon" />}
                      placeholder="账号"
                    />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[{ required: true, message: '请输入密码!' }]}
                  >
                    <Input.Password
                      prefix={<LockOutlined className="site-form-item-icon" />}
                      type="password"
                      placeholder="密码"
                      iconRender={(visible) =>
                        visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
                      }
                    />
                  </Form.Item>
                  <Form.Item
                    name="captcha_code"
                    rules={[{ required: true, message: '请输入验证码!' }]}
                  >
                    <Row gutter={2}>
                      <Col span={16}>
                        <Input
                          prefix={
                            <SafetyOutlined className="site-form-item-icon" />
                          }
                          placeholder="验证码"
                        />
                      </Col>
                      <Col span={8}>
                        <div
                          className={lr.captcha}
                          dangerouslySetInnerHTML={{ __html: captcha.img }}
                          onClick={() => {
                            getCaptcha({ key: captcha.key });
                          }}
                        />
                      </Col>
                    </Row>
                  </Form.Item>
                  <Form.Item>
                    <Button
                      type="primary"
                      htmlType="submit"
                      className="login-form-button"
                      block
                    >
                      登录
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <span>还没有成为我们的伙伴</span>
                    <Button
                      type="link"
                      onClick={() => {
                        setToggle(true);
                      }}
                    >
                      申请入驻
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
